#!/bin/bash
#
# Build ARM kernel 4.x.y and 5.x.y for
# QEMU Raspberry Pi Emulation
#
#######################################################

TOOLCHAIN=arm-linux-gnueabihf
COMMIT=""
# Change to true if you want to install the packages
INSTALL_PACKAGES=
# Change to true if you want to clone the repo (takes longer)
USE_GIT=
USB_WEBCAM_MODULES=""    # add USB & V4L modules for USB webcam support (didn't work as static)
KERNEL_MAKE_CONFIG=menuconfig # set to olddefconfig to skip user prompting
KERNEL_EXTRA_CONFIG=""

SOURCE_DIR=$(pwd)
BUILD_DIR=$SOURCE_DIR
TARGET_DIR=$SOURCE_DIR
                  
LINUX_ARCHIVE_SOURCE="https://github.com/raspberrypi/linux/archive/"

IFS=" " read -a kqemuconf   <<<`echo build-kernel-qemu.*`

BUILD_TARGET_CFG=${kqemuconf}

if [ -n $kqemuconf ] ; then

    for  modconf  in  ${!kqemuconf[*]} ; do
        echo -e "\t $(($modconf+1)) -> ${kqemuconf[${modconf}]}"
    done

    read  -p "Select kernel build : "

    if [  -z ${kqemuconf[$(($REPLY -1 ))]} ] ; then
        exit 1
    fi

    BUILD_TARGET_CFG=${kqemuconf[$(($REPLY -1))]}

fi

if [ -f $BUILD_TARGET_CFG ] ; then

    #+ load the configuration ...
    echo  "loading  build ->  $BUILD_TARGET_CFG"
    source  $BUILD_TARGET_CFG

fi

if [ -n "$INSTALL_PACKAGES" ] ; then
	echo "NOT EMPTY"
	sudo apt-get update
	sudo apt-get install git bc libncurses5-dev gcc-arm-linux-gnueabihf flex bison
fi

mkdir -p $BUILD_DIR $TARGET_DIR
CUR_DIR=$(pwd)
cd $BUILD_DIR

fetch_and_unpack_linux_archive ()  {  
    local commit_target=$1
    wget  -c   $LINUX_ARCHIVE_SOURCE${commit_target}.tar.gz -O   linux-${commit_target}.tar.gz  
    rm -rf  linux-${commit_target}  
    tar -xzvf linux-${commit_target}.tar.gz  
} 

if [ -n "$USE_GIT" ] ; then
	# checking out 4.x.y tag - change it if you want to change kernel version
	# for a specific hash, have a look at: https://github.com/raspberrypi/linux/tags
	# To check the effective kernel version, click on a tag in that list;
	# the branch and tag name are under the commit message.
	if [ ! -d linux ] ; then
		git clone https://github.com/raspberrypi/linux.git
	else
		echo "Using existing Linux sources!"
	fi
	cd linux
	if [ "$COMMIT" ] ; then
		git reset --hard
		git clean -xdf
		git checkout "$COMMIT"
	fi
else
	if [ -z "$COMMIT" ] ; then echo "COMMIT missing!" >&2 ; exit 1 ; fi
    if [ -d  linux-${COMMIT} ]   ;then 
         
        read  -p  "Found previews build directory :: linux-${COMMIT} use  it ? [y/n] "  
        case ${REPLY}  in 
            "y"|"Y" |"yes"|"YES")
                cd  linux-${COMMIT} 
                ;; 
                *)
                fetch_and_unpack_linux_archive ${COMMIT}  
                cd linux-${COMMIT}
                ;; 
        esac
    else 
        fetch_and_unpack_linux_archive ${COMMIT} 
        cd linux-${COMMIT}            
    fi 
fi

# Use all available cores for compilation
export MAKEFLAGS="$MAKEFLAGS -j$(nproc)"

KERNEL_VERSION=$(make kernelversion)
KERNEL_TARGET_FILE_NAME=$TARGET_DIR/qemu-kernel-$KERNEL_VERSION
MODULES_INSTALL_PATH=$TARGET_DIR/qemu-kernel-$KERNEL_VERSION-modules
if [ -e "../linux-arm-$KERNEL_VERSION.patch" ]; then
    patch -p1 < $SOURCE_DIR/linux-arm-$KERNEL_VERSION.patch
else
    patch -p1 < $SOURCE_DIR/linux-arm.patch
fi
make ARCH=arm versatile_defconfig
echo -e "##################################################################"
echo    " Building Qemu Raspberry Pi kernel qemu-kernel-$KERNEL_VERSION"
echo -e "##################################################################" 

if  [ -z  `command -v  ${TOOLCHAIN}-gcc` ]  ; then 
    #+NOTE: you need to  install  the toolchain first ...
    echo -e "Cannot found Toolchain cross compiler  <${TOOLCHAIN}> missing ... !"
    exit -1 
fi 
cat >> .config << EOF
CONFIG_CROSS_COMPILE="$TOOLCHAIN"
EOF

if [ -e "$SOURCE_DIR/config_file_$KERNEL_VERSION" ]; then
    cat "$SOURCE_DIR/config_file_$KERNEL_VERSION" >> .config
else
    cat "$SOURCE_DIR/config_file" >> .config
fi

if [ -e "$KERNEL_EXTRA_CONFIG" ]; then
    cat "$KERNEL_EXTRA_CONFIG" >> .config
fi

if [ $USB_WEBCAM_MODULES ] ; then
    echo "Make sure you have drivers for your webcam selected in menuconfig"
    cat $SOURCE_DIR/config_webcam >> .config
fi

cat $SOURCE_DIR/config_ip_tables >> .config
cat $SOURCE_DIR/config_loopdev >> .config

make -k ARCH=arm CROSS_COMPILE=${TOOLCHAIN}- $KERNEL_MAKE_CONFIG
make -k ARCH=arm CROSS_COMPILE=${TOOLCHAIN}- bzImage dtbs
cp arch/arm/boot/zImage $KERNEL_TARGET_FILE_NAME
if [ -e arch/arm/boot/dts/versatile-pb.dtb ] ; then
    cp arch/arm/boot/dts/versatile-pb.dtb $TARGET_DIR
fi

if [ $USB_WEBCAM_MODULES ] ; then
    mkdir -p $MODULES_INSTALL_PATH
    if [ ! -d $MODULES_INSTALL_PATH ] ; then
        echo "Couldn't create webcam modules install directory $MODULES_INSTALL_PATH"
    fi
    make -k ARCH=arm CROSS_COMPILE=${TOOLCHAIN}- modules
    make -k ARCH=arm CROSS_COMPILE=${TOOLCHAIN}- \
        INSTALL_MOD_PATH=$MODULES_INSTALL_PATH modules_install
    echo "Copy modules to Raspberry to /lib/modules/$KERNEL_VERSION"
fi

cd $CUR_DIR
